package com.ruoyi.web.controller.common;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.apache.ibatis.annotations.Many;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
@RestController
@RequestMapping("/oss")
public class OssUploadController {
    @Value("${oss.secretId}")
    private  String secretId;
    @Value("${oss.secretKey}")
    private  String secretKey;
    @Value("${oss.bucket}")
    private  String bucketName;
    @Value("${oss.region}")
    private  String region;
    @Value("${oss.baseUrl}")
    private  String baseUrl;

    //腾讯云cos对象存储
    @Anonymous
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception{
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            fileName = fileName.replace("/profile/upload", "");
            File localFile = new File(filePath + fileName);
            resizeImageIfNeeded(localFile, 1000);
            //上传oss
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName,localFile);
            COSClient cosClient = createCli();
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", baseUrl+fileName);
            ajax.put("fileName", baseUrl+fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return null;
        }
    }

    public void resizeImageIfNeeded(File imageFile, int maxWidth) throws Exception {
        String fileName = imageFile.getName();
        String ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
        String format = ("png".equals(ext) || "jpg".equals(ext) || "jpeg".equals(ext)) ? ext : "jpg";

        BufferedImage image = ImageIO.read(imageFile);
        if (image != null && image.getWidth() > maxWidth) {
            int newWidth = maxWidth;
            int newHeight = (int) ((double) image.getHeight() * newWidth / image.getWidth());
            int imageType = "png".equals(format) ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;
            Image tmp = image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
            BufferedImage resized = new BufferedImage(newWidth, newHeight, imageType);
            Graphics2D g2d = resized.createGraphics();
            g2d.drawImage(tmp, 0, 0, null);
            g2d.dispose();
            ImageIO.write(resized, format, imageFile);
        }
    }

    // 删除单个文件(不带版本号, 即bucket未开启多版本)
    @PostMapping("/delFile")
    private  void delSingleFile(String fileName) {
        try {
            COSClient cosClient = createCli();
            String key = fileName;
            cosClient.deleteObject(bucketName, key);
        } catch (CosServiceException e) { // 如果是其他错误, 比如参数错误， 身份验证不过等会抛出CosServiceException
            e.printStackTrace();
        } catch (CosClientException e) { // 如果是客户端错误，比如连接不上COS
            e.printStackTrace();
        }

    }
    private  COSClient createCli() {
        // 1 初始化用户身份信息(secretId, secretKey)

        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        return cosclient;
    }
}
